package cn.chenyumeng.blog.service.blog.impl;

import cn.chenyumeng.blog.dto.BlogDTO;
import cn.chenyumeng.blog.entity.Blog;
import cn.chenyumeng.blog.entity.BlogTag;
import cn.chenyumeng.blog.mapper.BlogMapper;
import cn.chenyumeng.blog.mapper.BlogTagMapper;
import cn.chenyumeng.blog.service.blog.ArchivesPageServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @program: blog->ArchivesPageServerImpl
 * @description:
 * @author: cg
 * @create: 2020-09-09 15:36
 **/
@Service
public class ArchivesPageServerImpl implements ArchivesPageServer {

    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private BlogTagMapper blogTagMapper;

    @Override
    public Map<Integer, List<BlogDTO>> getArchives() {
        List<Blog> blogs = blogMapper.queryBlogListByLatestPublishedAndDESCExcludeDescription();
        if (blogs.isEmpty()) {
            return null;
        }
        Map<Integer, List<BlogDTO>> map = new HashMap<>();
        List<BlogDTO> list = new ArrayList<>();
        blogs.forEach(blog -> {
            BlogDTO blogDTO = new BlogDTO();
            BeanUtils.copyProperties(blog, blogDTO);
            blogDTO.setTagIds(getTagIds(blogDTO.getId()));
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(blogDTO.getCreateTime());
            if (!map.containsKey(calendar.get(Calendar.YEAR))) {
                map.put(calendar.get(Calendar.YEAR), new ArrayList<>());
                map.get(calendar.get(Calendar.YEAR)).add(blogDTO);
            } else {
                map.get(calendar.get(Calendar.YEAR)).add(blogDTO);
            }
            list.add(blogDTO);
        });
        return map;
    }

    /**
     * 通过blogId查询所对应的tagIds
     * @param blogId
     * @return
     */
    private List<Long> getTagIds(Long blogId) {
        List<BlogTag> blogTags = blogTagMapper.selectBlogTagsByBlogId(blogId);
        List<Long> tags = new ArrayList<>();
        blogTags.forEach(blogTag -> tags.add(blogTag.getTagId()));
        return tags;
    }
}
